package com.example.demo.controller;

import com.example.demo.domain.Address;
import com.example.demo.domain.Order;
import com.example.demo.domain.User;
import com.example.demo.service.AddressService;
import com.example.demo.service.OrderService;
import com.example.demo.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AddressController {

    @Autowired
    private AddressService addressService;

    @Autowired
    private OrderService orderService;




    @PostMapping("/pay")
    public ModelAndView  chooseAddress(Integer oid,Integer addressId, ModelAndView view,HttpServletRequest request){

        System.out.println(oid+" "+addressId);

        Order order=orderService.getOrderById(oid);

        User user= (User) request.getSession().getAttribute("user");
        if(user==null){
            order.setUid(1);
        }else{
            order.setUid(user.getId());
        }
        order.setAid(addressId);
        order.setState(1);
        orderService.saveOrder(order);

        view.setViewName("redirect:/show/order/cart");

        return view;
    }


    @PostMapping("/address/add")
    public ModelAndView addAddress(Integer oid,String address,ModelAndView view, HttpServletRequest request){
        System.out.println(oid);

        User user= (User) request.getSession().getAttribute("user");
        if(user==null){
            addressService.addPartAddress(address,1,TimeUtils.getStringDate());
        }else{
            addressService.addPartAddress(address,user.getId(),TimeUtils.getStringDate());
        }

        view.setViewName("redirect:/show/address/choose/"+oid);

        return view;
    }


    @GetMapping("/show/address/choose/{oid}")
    public ModelAndView showAddressChoose(@PathVariable("oid") Integer oid,ModelAndView modelAndView,HttpServletRequest request){
        System.out.println(oid);

        User user= (User) request.getSession().getAttribute("user");
        List<Address> list;
        if(user==null){
            list=addressService.getAddressByUid(1);
        }else{
            list=addressService.getAddressByUid(user.getId());
        }
        System.out.println(list);
        modelAndView.addObject("oid",oid);
        modelAndView.addObject("list",list);
        modelAndView.setViewName("/show/address/choose");
        return modelAndView;
    }

    @GetMapping("/show/address/add/{oid}")
    public ModelAndView showAddressAdd(@PathVariable("oid") Integer oid,ModelAndView modelAndView){
        System.out.println(oid);

        modelAndView.setViewName("/show/address/add");
        modelAndView.addObject("oid",oid);

        return modelAndView;
    }

}
